package com.lei2j.observer;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lei2j on 2018/5/13.
 */
public class Subject {

    private static Map<String,Observer> observers = new HashMap<>();

    public String register(Observer object){
        if(observers.containsKey(object)){
            return "您已注册";
        }
        observers.put(String.valueOf(object.hashCode()),object);
        return "注册成功";
    }

    public void publish(String message){
        Collection<Observer> values = observers.values();
        for (Observer ob :
                values) {
            ob.subscribe(message);
        }
    }

    public void remove(Observer observer){
        String key = String.valueOf(observer.hashCode());
        if(observers.containsKey(key)){
           observers.remove(key);
        }
    }

    public static void main(String[] args) {
        Subject subject = new Subject();
        A1Observer a1Observer = new A1Observer();
        A2Observer a2Observer = new A2Observer();
        subject.register(a1Observer);
        subject.register(a2Observer);
        subject.publish("发布了。。。");
        subject.remove(a1Observer);
        subject.publish("再次发布了。。。");
    }

}